const Base = require('./base.js');

module.exports = class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
  async listAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;

    const query = this.get()

    if (query.name) {
      query.name = ['like', `%${query.name}%`]
    }

    delete query.page
    delete query.size

    const model = this.model('identity');
    const data = await model.where(query).order(['id DESC']).page(page, size).countSelect();

    return this.success(data);
  }

  async allAction() {

    const model = this.model('identity');
    const data = await model.order(['id DESC']).select()
    return this.success(data);
  }

  async putAction() {
    const values = this.post();
    const id = this.post('id');
    const model = this.model('identity');

    if (id > 0) {
      const old = await model.where({id: id}).find()
      if(old.name !== values.name){
        await model.where({id: id}).update(values);
        const list = await this.model('figure').where({identityTag: ['like',`%${old.name}%`]}).select()
        for (const item of list) {
          const arr = item.identityTag.split(',')
          for(var i = 0; i < arr.length; i++){
            if(arr[i] === old.name){
              arr[i] = values.name
            }
          }
          item.identityTag = arr.join(',')
        }
        await this.model('figure').updateMany(list)
      }
    } else {
      delete values.id;

      const hasUser = await model.where({name: values.name}).find()
      if(!think.isEmpty(hasUser)){
        return this.fail(400, '名称已存在');
      }
      values.create_time = ['exp', 'CURRENT_TIMESTAMP()']

      await model.add(values);
    }
    return this.success(values);
  }

  async deleteAction() {
    const id = this.get('id');

    const tag = await this.model('identity').where({id: id}).find()

    const list = await this.model('figure').where({identityTag: ['like',`%${tag.name}%`]}).select()

    for (const item of list) {
      const arr = item.identityTag.split(',')
      for(var i = 0; i < arr.length; i++){
        if(arr[i] === tag.name){
          arr.splice(i, 1);
        }
      }
      item.identityTag = arr.join(',')
    }
    await this.model('figure').updateMany(list)


    await this.model('identity').where({id: id}).limit(1).delete();

    return this.success();
  }
};
